package cn.anicert.zk.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.anicert.zk.bean.Node;
import cn.anicert.zk.bean.TreeNode;
import cn.anicert.zk.service.TreeNodeService;

@Controller
@RequestMapping("/zk/treeNode/v1")
public class TreeNodeController {
    private static final String NODE_SPRIT = "/";
    
    @Autowired
    private TreeNodeService     treeNodeService;
    
    @RequestMapping("index")
    public String zkIndex() {
        return "home/zookeeper_index";
    }
    
    @RequestMapping("/list")
    @ResponseBody
    public List<TreeNode> getAllTreeNode() {
        List<TreeNode> result = treeNodeService.getAllTreeNodeByPath(new ArrayList<TreeNode>(),
            "/");
        TreeNode root = new TreeNode();
        root.setNodeName("/");
        root.setNodePath("/");
        root.setNodeValue("");
        root.setParentNode(true);
        result.add(root);
        return result;
    }
    
    @RequestMapping("/getTreeNode")
    @ResponseBody
    public Node getTreeNode(@RequestParam String nodePath) {
        Node node = treeNodeService.readNode(nodePath);
        return node;
    }
    
    @RequestMapping("/addTreeNode")
    @ResponseBody
    public String addTreeNode(@RequestParam("curNodePath") String curNodePath,
        @RequestParam("newNodeName") String newNodeName) {
        TreeNode treeNode = new TreeNode();
        treeNode.setNodeName(newNodeName);
        treeNode.setNodePath(curNodePath + NODE_SPRIT + newNodeName);
        treeNode.setNodeValue("");
        if (!treeNodeService.isExistsTreeNode(treeNode)) {
            return String.valueOf(treeNodeService.addTreeNode(treeNode));
        } else {
            return "当前节点已存在";
        }
    }
    
    @RequestMapping("/deleteTreeNode")
    @ResponseBody
    public boolean deleteTreeNode(@RequestParam("nodePath") String nodePath) {
        TreeNode treeNode = new TreeNode();
        treeNode.setNodePath(nodePath);
        return treeNodeService.deleteTreeNode(treeNode);
    }
    
    @RequestMapping("/updateTreeNodeData")
    @ResponseBody
    public boolean updateTreeNodeData(@RequestParam("nodePath") String nodePath,
        @RequestParam("nodeValue") String nodeValue) {
        TreeNode treeNode = new TreeNode();
        treeNode.setNodePath(nodePath);
        treeNode.setNodeValue(nodeValue);
        return treeNodeService.updateTreeNodeData(treeNode);
    }
    
}
